import { Component, OnInit, Output, EventEmitter, Input, forwardRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RecipesManageService } from '../../../../shared/services/recipes.service';
import { ChannelManageService } from '../../../../shared/services/channel.service';
import { LabelManageService } from '../../../../shared/services/label.service';
import { MaterialManageService } from '../../../../shared/services/material.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { DictService } from '../../../../shared/services/dict.service';
import { LoginService } from '../../../../shared/services/login.service';

@Component({
  selector: 'app-detail-info',
  templateUrl: './detail-info.component.html',
  styleUrls: ['./detail-info.component.scss']
})
export class DetailInfoComponent implements OnInit {

  validateForm: FormGroup;

  modelType: any = '';
  typeSee: Boolean = false;

  _value = '';
  isVisible = false;    // alert
  _loading = false;
  isMaterialVisible = false;
  _allChecked = false;
  _indeterminate = false;
  _displayData = [];

  fileList = [];
  previewImage = '';
  previewVisible = false;

  recipeParams: any;

  // 渠道
  modalTitle: String = '';
  data = [];
  channelTree = [];

  // 原料弹窗对象
  materialAlertParams: any;

  infodata = [];

  expandDataCache = {};

  labelParams: any;

  rid = 0;

  unitDataType: any;

  searchMaterialType: any;

  centerItem: any;    // 新增面料删除中间件

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private loginService: LoginService,
    private dictService: DictService,
    private _message: NzMessageService,
    private materialManageService: MaterialManageService,
    private labelManageService: LabelManageService,
    private channelManageService: ChannelManageService,
    private recipesManageService: RecipesManageService,
    private fb: FormBuilder
  ) {
    // 自动联想搜索提示
    this.searchMaterialType = {
      timer: '',
      bool: false,
      title: '',
    };
  }

  ngOnInit() {
    // 页面正常逻辑开始
    this.reset();
    this.materialAlertReset();
    this.validateForm = this.fb.group({
      formLayout: [ 'horizontal' ],
      recipesName : [ null, [ Validators.required ] ],
      recipesSpecifications : [ null, [ Validators.required ] ],
      concatSelect : [ null, [ Validators.required ] ],
      channelPrice: null,
    });
    this.unitDataType = this.dictService.UnitDataType;
    // 获取方案负责人
    this.recipesManageService.getEmployeeList().subscribe(res => {
      // if (res['msg'] === '成功') {
        this.recipeParams.resPersonArray = res['data'];
      // }
    });
    // 解析获得参数导入
    this.route.queryParams
        .subscribe((pam: any) => {
          // console.log(pam);
          if (pam['type'] === 'see' || pam['type'] === 'edit') {
            this.recipeParams.id = pam['id'];
            this.recipesManageService.getRecipe(pam['id']).subscribe(res => {
              // console.log('detail : ', res);
              const that = this;
              // 查看
              if (res['data']) {
                const params = res['data'];
                // 名称
                this.recipeParams['name'] = params['name'];
                // 上下架
                this.recipeParams['pubStatus'] = params['pubStatus'];
                // SOP
                const reg = new RegExp('<br>', 'g'); // 创建正则RegExp对象
                if (params['sop']) {
                  this.recipeParams['sop'] = params['sop'].replace(reg, '\n');
                } else {
                  this.recipeParams['sop'] = '';
                }
                // 标签
                params['tagAttributes'].forEach(tag => {
                  this.recipeParams['tagAttributeIdsArray'].push({
                    id: tag.attributeId,
                    name: tag.attributeValue,
                    parent: {
                      id: tag.tagId,
                      name: tag.tagName,
                    }
                  });
                });
                // this.recipeParams['resPerson'] = params['resPerson'];
                // 成品规格
                this.recipeParams['specification'] = params['specification'];
                // 渠道
                // console.log(params['channels'])
                // this.recipeParams['channelIdsArray'].push(...params['channels']);
                params['channels'].forEach(chanl => {
                  this.recipeParams['channelIdsArray'].push({
                    id: chanl['channelId'],
                    name: chanl['name'],
                    price: chanl['price'],
                    parent: chanl['parent'],
                  });
                });
                // 食谱配方
                // recipeMaterialList = [ // 食谱配方
                //   {
                //     rid: this.rid,
                //     Material: {
                //       id: 0   // 原料id
                //     },
                //     name: '',
                //     goods: [],
                //     dosage: 1,  // 用量
                //     main: false,    // 主要原料
                //   }
                // ];
                this.recipeParams['recipeMaterialList'] = [];
                params['materials'].forEach(item => {
                  item.Material = {};
                  item['searchlist'] = [];
                  item['searchlist'].push(item);
                  this.recipeParams['recipeMaterialList'].push(item);
                });
                this.recipeParams['recipeMaterialList'].forEach(item => {
                  // console.log(item);
                  // console.log(item['searchlist']);
                  item.Material.id = item['searchlist'][0]['materialId'];
                  item.isNameShow = true;
                  // item.materialId = item['searchlist'][0]['id'];
                });
                // 如果没有，保底一条
                if (this.recipeParams['recipeMaterialList'].length < 1) {
                  this.recipeParams['recipeMaterialList'].push({
                    rid: this.rid,
                    Material: {
                      id: 0   // 原料id
                    },
                    name: '',
                    goods: [],
                    dosage: 0,  // 用量
                    main: false,    // 主要原料
                  });
                }
                // console.log(params)
                if (pam['type'] === 'see') {
                  this.typeSee = true;
                  this.modelType = 'see';
                  // 查看直接把负责人改成字符串
                  this.recipeParams.resPerson = params['resPerson'];
                }
                // 修改
                if (pam['type'] === 'edit') {
                  this.modelType = 'edit';
                  // 负责人
                  this.recipesManageService.getEmployeeList().subscribe(res => {
                    this.recipeParams['resPersonArray'] = res['data'];
                    const op = this.recipeParams['resPersonArray'].find(i => i['employeeName'] === params['resPerson']);
                    if (op) {
                      this.recipeParams.resPerson = op['employeeId'];
                    }
                  });
                }
                // console.log(that.recipeParams);
              }
            });
          } else {
            this.modelType = 'create';
          }
        });
  }

  reset() {
    this.recipeParams = {
      id: '',
      name: '',
      channelIds: [],       // 渠道id  数组
      channelIdsArray: [],  // 渠道弹窗返回数组
      sop: '',              // SOP
      tagAttributeIds: [],      // 标签id  数组
      tagAttributeIdsArray: [], // 标签 数组
      specification: '',    // 成品规格
      resPerson: '',        // 负责人
      resPersonArray: [],   // 负责人数组
      recipeMaterialList: [ // 食谱配方
        {
          rid: this.rid,
          Material: {
            id: 0   // 原料id
          },
          name: '',
          goods: [],
          dosage: 0,  // 用量
          main: false,    // 主要原料
        }
        // {
        //   Material: {
        //     id: 1   // 原料id
        //   },
        //   name: '',
        //   dosage: '1g',  // 用量
        //   main: true,    // 主要原料
        // }
      ]
    };
  }

  // tree start
  collapse(array, data, $event) {
    // console.log(array)
    // console.log(data)
    // console.log($event)
    if ($event === false) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.name === d.name);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root) {
    const stack = [], array = [], hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[ i ], level: node.level + 1, expand: false, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[ node.id ]) {
      hashMap[ node.id ] = true;
      array.push(node);
    }
  }
  // tree end

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
  }

  get isHorizontal() {
    return this.validateForm.controls[ 'formLayout' ] && this.validateForm.controls[ 'formLayout' ].value === 'horizontal';
  }

  _displayDataChange($event) {
    this._displayData = $event;
    this._refreshStatus();
  }

  _refreshStatus(e = '') {
    if (!e['checked']) {
      this._allChecked = false;
    }
    const allChecked = this._displayData.every(value => value.checked === true);
    const allUnChecked = this._displayData.every(value => !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = !allChecked && !allUnChecked;
  }

  locationAddMaterial() {
    this.router.navigate(['./add'], {
      relativeTo: this.route
    });
  }

  // 弹窗--渠道
  showModal = (type) => {
    this.isVisible = true;
    if (type === 'channel') {
      this.modalTitle = '选择渠道';
      // 获取所有渠道
      this.channelManageService.getChannelTree().subscribe(res => {
        // console.log('all channel: ', res);
        this.data = res['data'];
      });
    } else {
      this.modalTitle = '选择标签';
      this.labelManageService.getAllLabelList().subscribe(res => {
        // console.log('all labels:', res);
        this.data = res['data'];
        this.data.forEach(i => {
          if (i['optionals']) {
            i['children'] = [];
            i['optionals'].forEach(b => {
              i['children'].push({
                id: b['attributeId'],
                name: b['attributeValue']
              });
            });
          }
        });
      });
    }
    // console.log(this.data);
  }

  handleOk = (e) => {
    // console.log('点击了确定');
    this.isVisible = false;
  }
  handleCancel = (e) => {
    // console.log(e);
    this.isVisible = false;
  }

  // 弹窗 标签
  handleLabelCancel() {
    this.isMaterialVisible = false;
  }

  handleLabelOk() {
    this.isMaterialVisible = false;
  }

  handlePreview = (file) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

  _console(value) {
    // console.log(value);
  }

  delete(item) {
    // console.log(item);
  }

  // 格式化 弹窗树形展示
  _checkedInput($event) {
    const that = this;
    // console.log('当前点击对象 ', $event);
    // 让父级呈现半选状态
    const dat = this.concatObjDataToArray(this.data); // data
    $event['twoSelect'] = false;
    if ($event.parentId) {
      const op = dat.find(i => i['id'] === $event.parentId);
      if ($event.checked) {
        const opChildrenCheckd = op.children.every(value => value.checked === true);
        opChildrenCheckd ? op['checked'] = true : op['twoSelect'] = true;
      } else {
        let bool = 0;
        op.children.forEach(ele => {
          if (!ele['checked']) {
            bool++;
          }
        });
        if (bool === op.children.length) {
          op['checked'] = false;
          op['twoSelect'] = false;
        } else {
          op['checked'] = false;
          op['twoSelect'] = true;
        }
      }
      if (op.parentId) {
        const opt = dat.find(i => i['id'] === op.parentId);
        if ($event.checked) {
          const optChildrenCheckd = opt.children.every(value => value.checked === true);
          optChildrenCheckd ? opt['checked'] = true : opt['twoSelect'] = true;
        } else {
          let boold = 0;
          opt.children.forEach(ele => {
            if (!ele['checked']) {
              boold++;
            }
          });
          if (boold === opt.children.length) {
            opt['checked'] = false;
            let bol = 0;
            opt.children.forEach(iz => {
              if (iz['twoSelect'] === true) {
                bol++;
              }
            });
            if (bol > 0) {
              opt['twoSelect'] = true;
            } else {
              opt['twoSelect'] = false;
            }
          } else {
            opt['checked'] = false;
            opt['twoSelect'] = true;
          }
        }
      }
    }
    // 判断他下级是否存在
    if ($event['children']) {
      this.mapArraySet($event['children'], $event.checked);
    }
  }

  // 递归遍历数组赋值
  mapArraySet(array, bool) {
    const that = this;
    array.forEach(item => {
      item['checked'] = bool;
      if (item.children) {
        if (item.children.length > 0) {
          that.mapArraySet(item.children, bool);
        }
      }
    });
  }

  // 把对象组合成数组
  concatObjDataToArray(array) {
    const that = this;
    const concatArr = [];
    function mapArray(arr) {
      arr.forEach(item => {
        concatArr.push(item);
        if (item.children) {
          if (item.children.length > 0) {
            mapArray(item.children);
          }
        }
      });
    }
    mapArray(array);
    return concatArr;
  }

  // 表格数据跟 data 数据 apply
  dataApply(array) {
    const that = this;
    array.forEach(item => {
      for (const ide in that.expandDataCache) {
        that.expandDataCache[ide].forEach(ite => {
          if (ite['id'] === item['id']) {
            ite['checked'] = item['checked'];
          }
        });
      }
    });
  }

  // 渠道,标签弹窗确定
  // 如果是渠道：那么一定要有选择到三级，勾选了二级都么有用
  handleChannelOk(param) {
    const that = this;
    let deleteArr = [];
    deleteArr.push(...that.filterChildrenChecked(this.data));
    // 根据需求，渠道一定要选择到第三级，否则不能提交
    // 渠道：那么一定要有选择到三级，勾选了二级都么有用
    let channelLevelBool = false;
    if (this.modalTitle === '选择渠道') {
      deleteArr.forEach((item) => {
        if (item['parent']) {
          if (!item['parent']['parent']) {
            channelLevelBool = true;
          }
        } else {
          channelLevelBool = true;
        }
      });
    }
    if (channelLevelBool) {
      this._message.error('请选择3级渠道', {nzDuration: 4000});
      return false;
    }
    if (this.modalTitle === '选择标签') {
      deleteArr.forEach(item => {
        if (!this.recipeParams.tagAttributeIdsArray.find(i => i['id'] === item['id'])) {
          this.recipeParams.tagAttributeIdsArray.push(item);
        }
      });
    } else {
      deleteArr.forEach(item => {
        if (!this.recipeParams.channelIdsArray.find(i => i['id'] === item['id'])) {
          this.recipeParams.channelIdsArray.push(item);
        }
      });
    }
    this.isVisible = false;
  }

  // 过滤出所有子集
  filterChildrenChecked = (arr) => {
    const that = this;
    let backArr = [];
    let filterChildren = (array) => {
      array.forEach((item, index) => {
        if (item['children']) {
          item['children'].forEach(ite => {
            ite['parent'] = item;
          });
          filterChildren(item['children']);
        } else {
          if (item['checked']) {
            if (!backArr.find(i => i['id'] === item['id'])) {
              backArr.push(item);
            }
          }
        }
      });
    };
    filterChildren(arr);
    return backArr;
  }

  // 删除渠道
  channelDelete(channel, type) {
    if (type === 'channel') {
      this.recipeParams.channelIdsArray.splice(this.recipeParams.channelIdsArray.findIndex(i => i['id'] === channel['id']), 1);
    } else {
      this.recipeParams.tagAttributeIdsArray.splice(this.recipeParams.tagAttributeIdsArray.findIndex(i => i['id'] === channel['id']), 1);
    }
  }


  // materialAlert 操作
  // 弹窗-原料
  showMaterialModal = (item) => {
    this.centerItem = item;   // 面料删除中间件
    this.isMaterialVisible = true;
    this._allChecked = false;   // 关闭全选
    this._indeterminate = false;  // 关闭全选
    this.materialAlertReset();
    this.materialAlertGetData();
  }
  handleMaterialOk = (e) => {
    // 把原有的空对象给删了
    this.recipeParams.recipeMaterialList.splice(this.recipeParams.recipeMaterialList.findIndex(i => i['rid'] === this.centerItem['rid']), 1);
    // 过滤出选中数组，格式化后写入页面
    // console.log(this.materialAlertParams.data);
    this.materialAlertParams.data.forEach(item => {
      if (item['checked']) {
        // console.log('data', this.materialAlertParams.data)
        // console.log('recipeMaterialList', this.recipeParams.recipeMaterialList)
        const mater = this.recipeParams.recipeMaterialList.find(i => i['Material']['id'] === item['id']);
        if (!mater) {
          this.rid++; // 新增控制id
          this.recipeParams.recipeMaterialList.push({
            rid: this.rid,
            Material: {
              id: item.id   // 原料id
            },
            materialId: item.id,
            name: item.name,
            unit: item.unit,
            isNameShow: true,
            goods: item.goods,
            dosage: item.dosage || 0,  // 用量
            main: false,          // 主要原料
            searchlist: [
              {
                name: item.name,
                id: item.id,
                selected: true,
              }
            ]
          });
        }
      }
    });
    // console.log('data', this.recipeParams.recipeMaterialList);
    this.isMaterialVisible = false;
  }
  handleMaterialCancel = (e) => {
    // console.log(e);
    this.isMaterialVisible = false;
  }
  materialAlertReset() {
    this.materialAlertParams = {
      data: [],
      labelName: '',
      pageSize: 4,
      pageNumber: 1,
      totalPages: 0,
    };
  }

  materialAlertGetData() {
    this._loading = true;
    this.materialManageService.getmaterialList(this.materialAlertParams)
        .subscribe(res => {
          // console.log('原料数组列表', res);
          this.materialAlertParams.pageNumber = res['data']['pageNumber'];
          this.materialAlertParams.totalPages = res['data']['totalPages'] * this.materialAlertParams.pageSize;
          this.materialAlertParams.data = res['data']['list'];

          // 做个处理，外部已选列表在原料搜索列表里，如相同禁止选择
          this.materialAlertParams.data.forEach(item => {
            this.recipeParams.recipeMaterialList.forEach(ite => {
              if (item['id'] === ite['materialId']) {
                item.disabled = true;
              }
            });
          });
          // console.log('原料数组列表1', this.materialAlertParams.data);
          // console.log('原料数组列表2', this.recipeParams.recipeMaterialList);
          if (this._loading) {
            this._loading = false;
          }
        });
  }

  // 全选
  _checkAll(value) {
    if (value) {
      this.materialAlertParams.data.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.materialAlertParams.data.forEach(data => data.checked = false);
    }
    this._refreshStatus();
  }

  // 分页搜索
  pageChange(reset = false) {
    if (reset) {
      this.materialAlertGetData();
    }
  }

  onSearch(event: string): void {
    // console.log(event);
    this.materialAlertParams.labelName = event;
    this.materialAlertGetData();
  }

  searchMaterial($event, item) {
    // this.searchMaterialType = {
    //   timer: '',
    //   bool: false,
    //   title: '',
    // };
    // console.log($event);
    this.materialManageService.findByName($event).subscribe(res => {
      // console.log(res['data']);
      item.searchlist = res['data'];
    });
  }

  changeMaterialItem(item) {
    // console.log(item);
    const params = item.searchlist.find(i => i['id'] === item['Material']['id']);
    // console.log(params);
    const bool = this.recipeParams.recipeMaterialList.find(i => i['materialId'] === params['id']);
    if (!bool) {
      if (params) {
        // console.log('1', params)
        item.Material.id = params['id'];
        item.materialId = params['id'];
        item.dosage = params['dosage'] || 0;
        item.name = params['name'];
        item.unit = params['unit'];
        item.isNameShow = true;
        item.goods = params['goods'];
        this.addRecipesOData();
        // console.log('2', params)
      }
    } else {
      this._message.error('原料名为: ' + params['name'] + '的项已经存在，请重新选择。', {nzDuration: 4000});
    }
  }

  // 新增食谱配方
  addRecipesOData() {
    this.rid++; // 新增控制id
    this.recipeParams.recipeMaterialList.push({
      rid: this.rid,
      Material: {
        id: 0   // 原料id
      },
      name: '',
      goods: [],
      dosage: 0,  // 用量
      main: false,    // 主要原料
    });
  }

  // 删除食谱配方
  deleteRecipesOData(item) {
    if (this.recipeParams.recipeMaterialList.length > 1) {
      this.recipeParams.recipeMaterialList.splice(this.recipeParams.recipeMaterialList.findIndex(i => i['materialId'] === item['materialId']), 1);
    }
  }

  // 最后数据递交保存
  saveInfo() {
    // console.log('最终提交数据:', this.recipeParams);
    this.submitForm();
    // 食谱名称
    if (!this.recipeParams.name) {
      this._message.error('请输入食谱名称', {nzDuration: 3000});
      return false;
    }
    // 渠道
    if (this.recipeParams.channelIdsArray.length < 1) {
      this._message.error('请选择渠道', {nzDuration: 3000});
      return false;
    }
    // 渠道价格数据有空
    const bool = this.recipeParams.channelIdsArray.every(value => value['price']);
    if (!bool) {
      this._message.error('渠道的市场价是必填，请重新填写', {nzDuration: 3000});
      return false;
    }
    // 标签
    if (this.recipeParams.tagAttributeIdsArray.length < 1) {
      this._message.error('请选择标签', {nzDuration: 3000});
      return false;
    }
    // 成品规格
    if (!this.recipeParams.specification) {
      this._message.error('请输入成品规格', {nzDuration: 3000});
      return false;
    }
    // 方案负责人
    if (!this.recipeParams.resPerson) {
      this._message.error('请选择方案负责人', {nzDuration: 3000});
      return false;
    }
    // 过滤去除空值的原料
    let recipeMaterialList = [];
    this.recipeParams.recipeMaterialList.forEach(item => {
      if (item.name) {
        recipeMaterialList.push(item);
      }
    });
    // 食谱配方
    if (recipeMaterialList.length < 1) {
      this._message.error('请选择食谱配方', {nzDuration: 3000});
      return false;
    }
    // 已填写的食谱必须填写用量
    let dosageBool = false;
    recipeMaterialList.forEach(item => {
      if (!item['dosage'] || item['dosage'] == 0) {
        dosageBool = true;
      }
    });
    if (dosageBool) {
      this._message.error('已填写的食谱配方必须填写用量，请重新检查', {nzDuration: 3000});
      return false;
    }

    if (!this.recipeParams.sop) {
      this._message.error('请填写操作步骤', {nzDuration: 3000});
      return false;
    }

    // 验证sop字数是否超过500
    if (this.recipeParams.sop.length > 500) {
      this._message.error('SOP字数超过最大限制500个字符，请修改后提交!', {nzDuration: 3000});
      return false;
    }

    // 格式化sop换行
    if (this.recipeParams.sop) {
      this.recipeParams.sop =  this.recipeParams.sop.replace(/\n|\r\n/g, '<br>');
    }

    // 到这，通过验证
    this.recipeParams.recipeMaterialList = recipeMaterialList;

    // console.log('params:', this.recipeParams);

    // 把负责人id 格式化成 人名
    // resPerson: '',        // 负责人
    // resPersonArray: [],   // 负责人数组
    // this.recipeParams.resPersonArray.forEach(res => {
    //   if (res['employeeId'] === this.recipeParams.resPerson) {
    //     this.recipeParams.resPersonName = res['employeeName'];
    //   }
    // });

    // console.log('最终提交参数', this.recipeParams);

    // if(true){
    //   return false;
    // }

    if (this.modelType === 'edit') {
      this.recipesManageService.postUpdateRecipes(this.recipeParams).subscribe(res => {
        // console.log(res);
        if (res['code'] === '0') {
          this._message.success('修改食谱成功', {nzDuration: 2000});
          this.goback();
        } else {
          this._message.error('修改食谱失败,' + res['msg'], {nzDuration: 3000});
        }
      });
    } else {
      this.recipesManageService.postCreateRecipes(this.recipeParams).subscribe(res => {
        // console.log(res);
        if (res['code'] === '0') {
          this._message.success('新增食谱成功', {nzDuration: 2000});
          this.goback();
        } else {
          this._message.error('新增食谱失败,' + res['msg'], {nzDuration: 3000});
        }
      });
    }
  }

  goback() {
    this.router.navigate(['../'], { relativeTo: this.route, queryParamsHandling: 'preserve' });
  }

  // 限制sop输入字数
  sopInputChange(sop) {
    if (sop.length > 499) {
      this.recipeParams.sop = sop.substr(0, 499);
      document.getElementsByClassName('infoSopTextarea')[0]['value'] = sop.substr(0, 499);
    }
  }

}
